/*
 * @Author: xushuhao
 * @Email: xshmouse@163.com
 * @Date: 2020-04-18 18:43:53
 * @Last Modified by: xushuhao
 * @Last Modified time: 2020-06-23 13:35:17
 * @Description: 全局公用类 - 待完善
 */

import 'dart:io';
import 'dart:ui';

import 'package:event_bus/event_bus.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_code_framework/network/request.dart';
import 'package:flutter_code_framework/utils/user.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:open_file/open_file.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:path_provider/path_provider.dart';
import 'package:url_launcher/url_launcher.dart';
import 'message_dialog.dart';
import 'package:flutter_downloader/flutter_downloader.dart';

/// global
class G {
  static final GlobalKey<NavigatorState> navigatorKey = GlobalKey();

  static final EventBus eventBus = EventBus();

  static final String appID = ''; //APP包名

  /// toolbar routeName
  static final List toobarRouteNameList = [
    '/lessons_page',
    '/classroom_page',
    '',
    '/resources_page',
    '/my_page',
    '/login'
  ];

  static int tabIndex = 0; //当前tabbar index

  /// 手动延时
  static sleep({int milliseconds = 1000}) async =>
      await Future.delayed(Duration(milliseconds: milliseconds));

  /// 下拉刷新样式
  //static final PullToRefreshStyle pullToRefreshStyle = PullToRefreshStyle();

  /// 获取当前的state
  static NavigatorState getCurrentState() => navigatorKey.currentState;

  /// 获取当前的context
  static BuildContext getCurrentContext() => navigatorKey.currentContext;

  /// 获取屏幕上下边距
  /// 用于兼容全面屏，刘海屏
  static EdgeInsets screenPadding() =>
      MediaQuery.of(getCurrentContext()).padding;

  /// 获取屏幕宽度
  static double screenWidth() => MediaQuery.of(getCurrentContext()).size.width;

  /// 获取屏幕高度
  static double screenHeight() =>
      MediaQuery.of(getCurrentContext()).size.height;

  /// 跳转页面使用 G.pushNamed
  static void pushNamed(String routeName, {Object arguments}) {
    // 如果跳转到toolbar页面  不能返回
    if (toobarRouteNameList.indexOf(routeName) > -1) {
      getCurrentState().pushReplacementNamed(
        routeName,
        arguments: arguments,
      );
    } else {
      getCurrentState().pushNamed(routeName, arguments: arguments);
    }
  }

  /// 返回页面
  static void pop() => getCurrentState().pop();

  /// 底部border
  /// ```
  /// @param {Color} color
  /// @param {bool} show  是否显示底部border
  /// ```
  static Border borderBottom({Color color, bool show = true}) {
    return Border(
        bottom: BorderSide(
            color: (color == null || !show)
                ? (show ? Color.fromRGBO(242, 242, 242, 1) : Colors.transparent)
                : color,
            width: 1));
  }

  /// 获取时间戳
  /// 不传值 代表获取当前时间戳
  static int getTime([DateTime time]) {
    if (time == null) {
      return (DateTime.now().millisecondsSinceEpoch / 1000).round();
    } else {
      return (time.millisecondsSinceEpoch / 1000).round();
    }
  }

  ///弹对话框
  static void showToastDialog(BuildContext context, String message,
      {String title = "提示",
      String positiveText = "确定",
      String negativeText = "取消",
      Function callBack}) {
    if (context != null) {
      if (message != null && message.isNotEmpty) {
        showDialog<Null>(
            context: context, //BuildContext对象
            barrierDismissible: false,
            builder: (BuildContext context) {
              //调用对话框
              return MessageDialog(
                title: title,
                negativeText: negativeText,
                positiveText: positiveText,
                message: message,
                onCloseEvent: () {
                  Navigator.pop(context);
                },
                onPositivePressEvent: () {
                  Navigator.pop(context);
                  if (callBack != null) {
                    callBack();
                  }
                },
              );
            });
      }
    }
  }

  static Future toast(String text) {
    return Fluttertoast.showToast(
        msg: text,
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 5,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0);
  }

  ///弹吐司 - 普通提示
  ///Fluttertoast.cancel();
  static showNormalToast(String content,
      {Toast length = Toast.LENGTH_SHORT,
      ToastGravity gravity = ToastGravity.BOTTOM,
      Color backColor = G.ToastNormalBackgroundColor,
      // Color textColor = G.buttonTextColor,
      int timeInSecForIosWeb = 2}) {
    Fluttertoast.showToast(
        msg: content,
        gravity: gravity,
        backgroundColor: backColor,
        // textColor: textColor,
        timeInSecForIosWeb: timeInSecForIosWeb);
  }

  ///弹吐司 - 正向提示
  static showRightToast(String content,
      {Toast length = Toast.LENGTH_SHORT,
      ToastGravity gravity = ToastGravity.BOTTOM,
      Color backColor = G.ToastRightBackgroundColor,
      // Color textColor = G.buttonTextColor,
      int timeInSecForIosWeb = 2}) {
    Fluttertoast.showToast(
        msg: content,
        gravity: gravity,
        backgroundColor: backColor,
        // textColor: textColor,
        timeInSecForIosWeb: timeInSecForIosWeb);
  }

  ///弹吐司 - 警告、错误提示
  static showWrongToast(String content,
      {Toast length = Toast.LENGTH_SHORT,
      ToastGravity gravity = ToastGravity.BOTTOM,
      Color backColor = G.ToastWrongBackgroundColor,
      // Color textColor = G.buttonTextColor,
      int timeInSecForIosWeb = 2}) {
    Fluttertoast.showToast(
        msg: content,
        gravity: gravity,
        backgroundColor: backColor,
        // textColor: textColor,
        timeInSecForIosWeb: timeInSecForIosWeb);
  }

  ///Toast 背景色 - 正向反馈
  static const Color ToastRightBackgroundColor =
      Color.fromRGBO(57, 135, 110, 0.9);

  ///Toast 背景色 - 正向反馈
  static const Color ToastWrongBackgroundColor =
      Color.fromRGBO(236, 115, 100, 0.9);

  ///Toast 背景色 - 正向反馈
  static const Color ToastNormalBackgroundColor = Color.fromRGBO(0, 0, 0, 0.8);

  /// user信息
  static final User user = User();

  /// 初始化request
  static final Request req = Request();

  // 申请权限
  static Future<bool> checkPermission(BuildContext context) async {
    // 先对所在平台进行判断
    if (Theme.of(context).platform == TargetPlatform.android) {
      PermissionStatus permission = await PermissionHandler()
          .checkPermissionStatus(PermissionGroup.storage);
      if (permission != PermissionStatus.granted) {
        Map<PermissionGroup, PermissionStatus> permissions =
            await PermissionHandler()
                .requestPermissions([PermissionGroup.storage]);
        if (permissions[PermissionGroup.storage] == PermissionStatus.granted) {
          return true;
        }
      } else {
        return true;
      }
    } else {
      return true;
    }
    return false;
  }

  // 获取存储路径
  static Future<String> findLocalTempPath() async {
    // 因为Apple没有外置存储，所以第一步我们需要先对所在平台进行判断
    // 如果是android，使用getExternalStorageDirectory
    // 如果是iOS，使用getApplicationSupportDirectory
    final directory = Platform.isAndroid
        ? await getExternalStorageDirectory() //getTemporaryDirectory()getExternalStorageDirectory()
        : await getApplicationSupportDirectory();
    return directory.path;
  }

  static Future<String> createFileDir(String subPath) async {
    // 获取存储路径
    var _localPath = (await findLocalTempPath()) + '/Download/' + subPath;

    Directory savedDir = Directory(_localPath);
    // 判断下载路径是��存在
    bool hasExisted = await savedDir.exists();
    // 不存在就新建路径
    if (!hasExisted) {
      // savedDir.create();
      savedDir.createSync(recursive: true);
    }

    return _localPath;
  }

  static openToAppStore(String url) async {
    if (await canLaunch(url)) {
      await launch(
        url,
        // forceSafariVC: false,
        // forceWebView: false,
        // headers: <String, String>{'my_header_key': 'my_header_value'},
      );
    } else {
      throw 'Could not launch $url';
    }
  }

  static Future<void> openFile(String filePath) async {
    final result = await OpenFile.open(
      filePath,
    );
    // print("type=${result.type}  message=${result.message}");
  }

  // 根据taskId打开下载文件
  static Future<bool> _openDownloadedFile(taskId) {
    return FlutterDownloader.open(taskId: taskId);
  }

  static final ThemeData brigtTheme = ThemeData(
    brightness: Brightness.light,
    primaryColor: Color.fromRGBO(57, 135, 110, 1), //主色 （创课绿）
    primaryColorBrightness: Brightness.dark, // 主色上方文本、图标颜色  默认：light 黑； dark 白
    primaryColorDark: null, //主色 深
    primaryColorLight: null, //主色 浅
    cardColor: Color.fromRGBO(216, 216, 216, 0.5), //过滤条件栏背景
    primaryTextTheme: TextTheme(
      headline1: TextStyle(
        color: Color.fromRGBO(34, 34, 34, 1),
        fontSize: 28,
      ), //弹出页大标题 28
      headline2: TextStyle(
        color: Color.fromRGBO(72, 72, 72, 1),
        fontSize: 28,
      ), // 提示页标题弹出页标题 28
      headline3: TextStyle(
        color: Color.fromRGBO(34, 34, 34, 1),
        fontSize: 24,
      ), // 独立页标题  24
      headline4: TextStyle(
        color: Color.fromRGBO(72, 72, 72, 0.7),
        fontSize: 16,
      ), // 页副标题 16
      caption: TextStyle(
        color: Color.fromRGBO(118, 118, 118, 1),
        fontSize: 22,
      ), //TAB页标题 22
      subtitle1: TextStyle(
        color: Color.fromRGBO(118, 118, 118, 1),
        fontSize: 12,
      ), //TAB页副标题 12
      headline6: TextStyle(
        color: Color.fromRGBO(124, 124, 124, 1),
        fontSize: 28,
      ), //标题 18
      subtitle2: TextStyle(
        color: Color.fromRGBO(118, 118, 118, 1),
        fontSize: 14,
      ), //副标题 14
      headline5: TextStyle(
        color: Color.fromRGBO(57, 135, 110, 1),
        fontSize: 14,
      ), //过滤标题 主色 14

      button: TextStyle(color: Colors.white), //按钮字体色
    ),
    accentColor: Color.fromRGBO(236, 115, 100, 1), //突出色
    accentColorBrightness: Brightness.dark, //child color light 黑； dark 白
    backgroundColor: Color.fromRGBO(255, 255, 255, 1), //背景
    scaffoldBackgroundColor: Color.fromRGBO(255, 255, 255, 1),
    errorColor: Color.fromRGBO(236, 115, 100, 1), //错误
    disabledColor: Color.fromRGBO(235, 235, 235, 1), //不可用
    dialogBackgroundColor: Color.fromRGBO(221, 221, 221, 0.75), //对话框蒙层背景
    dividerColor: Color.fromRGBO(235, 235, 235, 1), //分割线颜色
    hintColor: Color.fromRGBO(57, 135, 110, 1), // 提示信息颜色
    textSelectionColor: Color.fromRGBO(249, 249, 249, 1), //文本区域底色
    cursorColor: Color.fromRGBO(181, 181, 181, 1), //光标 或 输入框左侧图标
  );

  //启用时自定义并追加 brightness: Brightness.dark,

  static final ThemeData darkTheme =
      brigtTheme.copyWith(brightness: Brightness.dark);
  //字体颜色对应备忘 34=209； 72=100； 118=47；  headline5 = 35； backgroundColor：35 ；
  //cardColor : 25

  static CupertinoButton getNormalButton(Widget child, Function fun) {
    return CupertinoButton(
      color: Color.fromRGBO(57, 135, 110, 1),
      padding: EdgeInsets.fromLTRB(50, 5, 50, 5),
      child: child,
      onPressed: fun,
    );
  }

  /// 颜色创建方法
  /// - [colorString] 颜色值
  /// - [alpha] 透明度(默认1，0-1)
  ///
  /// 可以输入多种格式的颜色代码，如: 0x000000,0xff000000,#000000
  static Color ADColor(String colorString, {double alpha = 1.0}) {
    String colorStr = colorString;
    // colorString未带0xff前缀并且长度为6
    if (!colorStr.startsWith('0xff') && colorStr.length == 6) {
      colorStr = '0xff' + colorStr;
    }
    // colorString为8位，如0x000000
    if (colorStr.startsWith('0x') && colorStr.length == 8) {
      colorStr = colorStr.replaceRange(0, 2, '0xff');
    }
    // colorString为7位，如#000000
    if (colorStr.startsWith('#') && colorStr.length == 7) {
      colorStr = colorStr.replaceRange(0, 1, '0xff');
    }
    // 先分别获取色值的RGB通道
    Color color = Color(int.parse(colorStr));
    int red = color.red;
    int green = color.green;
    int blue = color.blue;
    // 通过fromRGBO返回带透明度和RGB值的颜色
    return Color.fromRGBO(red, green, blue, alpha);
  }
}
